<?php

    class PostController extends AdminController
    {
        public function init(){
            parent::init();
            $this->menu_parent_selected = 'post';

        }

        /**
        * @return array action filters
        */
        public function filters()
        {
            return array(
                'accessControl', // perform access control for CRUD operations
                'postOnly + delete', // we only allow deletion via POST request
            );
        }

        /**
        * Specifies the access control rules.
        * This method is used by the 'accessControl' filter.
        * @return array access control rules
        */
        public function accessRules()
        {
            return array(
                array('allow',
                    'actions'=>array('view'),
                    'users'=>array('*'),
                ),
                array('allow', // allow authenticated user to perform 'create' and 'update' actions
                    'actions'=>array('create', 'index', 'delete', 'update'),
                    'users'=>array('@'),
                ),
                array('deny',  // deny all users
                    'users'=>array('*'),
                ),
            );
        }

        public function actionIndex()
        {
            $this->menu_child_selected = 'post';
            $this->menu_sub_selected = 'index';

            $model = new Post('search');
            $model->unsetAttributes();  // clear any default values
            if(isset($_GET['Post'])) $model->attributes=$_GET['Post'];


            $criteria=new CDbCriteria;

            $sort = Yii::app()->request->getQuery('Post_sort');

            if(!$sort && $sort != 'id') $criteria->order = 't.id DESC'; 
            $criteria->compare('t.id',$model->id,true);
            $criteria->compare('t.title',$model->title,true);
            $criteria->compare('t.desc',$model->desc,true);
            $criteria->compare('t.content',$model->content,true);
            $criteria->compare('t.cat_id',$model->cat_id,true);
            $criteria->compare('t.created',$model->created,true);
            $criteria->compare('t.status',$model->status,true);
            $criteria->compare('t.manager_id',$model->manager_id,true);

            $dataProvider = new CActiveDataProvider($model, array(
                'criteria'=>$criteria,
                'pagination'=>array(
                    'pageSize'=>20,
                ),
            ));

            $this->render('index',array(
                'model'         =>  $model,
                'dataProvider'         =>  $dataProvider,
            ));
        }

        /**
        * Creates a new model.
        * If creation is successful, the browser will be redirected to the 'view' page.
        */
        public function actionCreate()
        {
            $this->menu_child_selected = 'post_create';
            $this->menu_sub_selected = 'create';


            $model=new Post('create');
            $model->setIsNewRecord(true);

            $imgConf = Yii::app()->params->post_img;
            $uploadEditorPathTemp = $imgConf['path']."temp/{$this->manager->id}/content/";
            Myext::createDir($uploadEditorPathTemp);

            $ps = array(); // paragraphs
            if(isset($_POST['Post']))
            {    
                Yii::import('ext.MyDateTime');
                $post = Yii::app()->request->getPost('Post');
                //             echo "<pre>";print_r($post);echo "</pre>";die;
                $model->attributes=$post;

                $model->created = $model->created ? $model->created : MyDateTime::getCurrentTime();

                $model->manager_id = $model->manager_id ? $model->manager_id : $this->manager->id;

                if($model->validate()) {
                    Yii::import('ext.TextParser');
                    $model->alias = TextParser::toSEOString($model->title);
                    $model->alias_en = TextParser::toSEOString($model->title_en);
                    $model->setIsNewRecord(TRUE);   
                    $model->insert();


                    /////// IMAGES ////////
                    $postPath = $imgConf['path']."{$model->id}/";
                    Myext::createDir($postPath);

                    $source = NULL;
                    if($post['upload_method'] == 'file'){
                        $source = 'browse_file';
                    }else{
                        $source = $post['image_url'];
                    }  


                    Yii::import('ext.wideimage.lib.WideImage');  
                    $img = WideImage::load($source);

                    $model->image = $model->alias;

                    foreach($imgConf['cover'] as $type => $conf){
                        $img = $img->resize($conf['width'], $conf['height'], 'outside', 'down');
                        $img = $img->resizeCanvas($conf['width'], $conf['height'],'center','center', null, 'down');
                        $img->saveToFile($postPath.$model->image."_{$type}.jpg", 90);  
                    }


                    if(trim($model->content)){
                        // add baseUrl to temp images
                        Yii::import('ext.simple_html_dom');
                        $html = new simple_html_dom($model->content);
                        foreach($html->find('img') as $i => $img){
                            if(preg_match('{^/'.$uploadEditorPathTemp.'.+$}', $img->src)){
                                $img->src = $this->baseUrl.$img->src;
                            }
                        }
                        $content = $html->save();

                        // upload content images
                        Yii::import('ext.Myext');   
                        $model->content = Myext::saveContentImages($content, $postPath, array(
                            'image_x' => $imgConf['body']['width'],
                            'image_y' => $imgConf['body']['height'],
                            ), $model->alias);  
                    }


                    if(trim($model->content_en)){
                        // add baseUrl to temp images
                        Yii::import('ext.simple_html_dom');
                        $html = new simple_html_dom($model->content_en);
                        foreach($html->find('img') as $i => $img){
                            if(preg_match('{^/'.$uploadEditorPathTemp.'.+$}', $img->src)){
                                $img->src = $this->baseUrl.$img->src;
                            }
                        }
                        $content = $html->save();

                        // upload content images
                        Yii::import('ext.Myext');   
                        $model->content_en = Myext::saveContentImages($content, $postPath, array(
                            'image_x' => $imgConf['body']['width'],
                            'image_y' => $imgConf['body']['height'],
                            ), $model->alias_en);  
                    }

                    // remove temp images
                    Myext::deleteDir($uploadEditorPathTemp, FALSE);


                    // post to facebook page && twitter
                    if($model->status == 'PUBLISH' && ($post['post_fb'])){
                        $model->postFacebook();
                        $model->fb_posted = MyDateTime::getCurrentTime();
                    }

                    $model->update();

                    Post::model()->submitSitemap();
                    PostCat::model()->updatePostCount();

                    Yii::app()->user->setFlash('success', "Post {$model->title} was added successful!");
                    $this->refresh();
                }
            }

            $this->render('form',array(
                'model'=>$model,
                'ps'=>$ps,
                'uploadEditorPath'=>$uploadEditorPathTemp,
            ));
        }



        /**
        * Updates a particular model.
        * If update is successful, the browser will be redirected to the 'view' page.
        * @param integer $id the ID of the model to be updated
        */
        public function actionUpdate($id)
        {
            $this->menu_child_selected = 'post_update';
            $this->menu_sub_selected = 'update';

            $model = Post::model()->findByPk($id);
            $model->scenario = 'update';


            $imgConf = Yii::app()->params->post_img;
            $contentPath = $imgConf['path']."{$model->id}/";
            Myext::createDir($contentPath);

            if(isset($_POST['Post']))
            {    
                Yii::import('ext.MyDateTime');
                $post = Yii::app()->request->getPost('Post');
                //             echo "<pre>";print_r($post);echo "</pre>";die;
                $model->attributes=$post;

                if(!$model->created || $model->created == '0000-00-00 00:00:00'){
                    $model->created = MyDateTime::getCurrentTime();
                }

                $model->changed = MyDateTime::getCurrentTime();

                if($model->validate()) {
                    Yii::import('ext.TextParser');
                    $model->alias = TextParser::toSEOString($model->title);
                    $model->alias_en = TextParser::toSEOString($model->title_en);
                    $model->setIsNewRecord(FALSE);


                    /////// IMAGES ////////
                    $path = $imgConf['path']."{$model->id}/";
                    if(!file_exists($path)) mkdir($path,0777,true);

                    $content_h = $imgConf['body']['height'];
                    $content_w = $imgConf['body']['width'];

                    if(
                        ($post['upload_method'] == 'file' && $_FILES['browse_file']['size']) || 
                        ($post['upload_method'] == 'url' && $post['image_url'])
                    ){
                        $source = NULL;
                        if($post['upload_method'] == 'file'){
                            $source = 'browse_file';
                        }else{
                            $source = $post['image_url'];
                        }  

                        Yii::import('ext.wideimage.lib.WideImage');  
                        $img = WideImage::load($source);

                        $model->image = $model->alias;

                        foreach($imgConf['cover'] as $type => $conf){
                            $img = $img->resize($conf['width'], $conf['height'], 'outside', 'down');
                            $img = $img->resizeCanvas($conf['width'], $conf['height'],'center','center', null, 'down');
                            $img->saveToFile($path.$model->image."_{$type}.jpg", 90);  
                        }
                    }


                    if(trim($model->content)){
                        // upload content images
                        Yii::import('ext.Myext');   
                        $model->content = Myext::saveContentImages($model->content, $path, array(
                            'image_x' => $content_w,
                            'image_y' => $content_h,
                        ), $model->alias);  
                    } 
                    
                    if(trim($model->content_en)){
                        // upload content images
                        Yii::import('ext.Myext');   
                        $model->content_en = Myext::saveContentImages($model->content_en, $path, array(
                            'image_x' => $content_w,
                            'image_y' => $content_h,
                        ), $model->alias_en);  
                    } 

                    // post to facebook page && twitter
                    if($model->status == 'PUBLISH' && $post['post_fb']){
                        if($post['post_fb']){
                            $model->postFacebook();
                            $model->fb_posted = MyDateTime::getCurrentTime();
                        }
                    }

                    $model->update();

                    Post::model()->submitSitemap();

                    Yii::app()->user->setFlash('success', "Post {$model->title} was updated successful!");
                    $this->refresh();
                }
            }


            $this->render('form',array(
                'model'=>$model,
                'uploadEditorPath'=>$contentPath,
            ));
        }

        /**
        * Deletes a particular model.
        * If deletion is successful, the browser will be redirected to the 'admin' page.
        * @param integer $id the ID of the model to be deleted
        */
        public function actionDelete($id)
        {
            $model = $this->loadModel($id);
            $model->delete();

            $imgConf = Yii::app()->params->post_img;
            $moviePath = $imgConf['path']."{$id}/";

            Myext::deleteDir($moviePath);

            // if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
            if(!isset($_GET['ajax'])) $this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('index'));
        }


        public function actionView($q)
        {
            return Yii::app()->db->createCommand($q)->query();
        }


        /**
        * Returns the data model based on the primary key given in the GET variable.
        * If the data model is not found, an HTTP exception will be raised.
        * @param integer the ID of the model to be loaded
        */
        public function loadModel($id)
        {
            $model=Post::model()->findByPk($id);
            if($model===null)
                throw new CHttpException(404,'The requested page does not exist.');
            return $model;
        }

    }
